package net.wicp.tams.common.tracer.agent;

import java.math.BigInteger;

import javax.servlet.http.HttpServletRequest;

import javassist.CtMethod;
import net.wicp.tams.common.tracer.AnnotationNames;
import net.wicp.tams.common.tracer.Annotations;
import net.wicp.tams.common.tracer.HttpHeaderNames;
import net.wicp.tams.common.tracer.Span;
import net.wicp.tams.common.tracer.SpanHelper;

public class TraceAgent {

	public void aaa(CtMethod method, HttpServletRequest request) {
		final String name = String.format("%s %s", new Object[] { request.getMethod(), request.getRequestURL() });
		Span span;
		span = SpanHelper.startTrace(name);

		String traceId = request.getHeader(HttpHeaderNames.TRACE_ID);
		String spanId = request.getHeader(HttpHeaderNames.SPAN_ID);
		if (traceId == null) {
			traceId = String.valueOf(span.getTraceId());
		}
		if (spanId == null) {
			spanId = String.valueOf(span.getSpanId());
		}
		org.slf4j.MDC.put("traceId", traceId);
		org.slf4j.MDC.put("spanId", spanId);
		System.out.println("this is traceId:" + traceId);
		if (traceId != null && spanId != null) {
			BigInteger traceIdLong = new BigInteger(traceId);
			BigInteger spanIdLong = new BigInteger(spanId);
			span = SpanHelper.startSpan(traceIdLong, spanIdLong, name);
		} else {
			span = SpanHelper.startTrace(name);
		}

		try {
			span.addAnnotation(AnnotationNames.SERVER_RECEIVED);
			span.addAnnotation(AnnotationNames.SERVICE_NAME, Annotations.getServiceAnnotations().getService());
			// $proceed($$);
		} finally {
			span.addAnnotation(AnnotationNames.SERVER_SENT);
			span.end();
		}
	}
}
